package com.jxm.spring.security.security;

import com.jxm.spring.security.bean.Menu;
import com.jxm.spring.security.security.domain.SysUserDetails;
import com.jxm.spring.security.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author: jxm
 * @Description: 用户权限注解处理类
 * @Date: 2021/5/16 19:45
 * @Version: 1.0
 */
@Component
public class UserPermissionEvaluator implements PermissionEvaluator{

    @Autowired
    private IUserService userService;

    /**
     * 判断是否拥有权限
     * @param authentication 用户身份
     * @param targetUrl 目标路径
     * @param permission 路径权限
     * @return
     */
    @Override
    public boolean hasPermission(Authentication authentication, Object targetUrl, Object permission) {
        SysUserDetails sysUserDetails = (SysUserDetails) authentication.getPrincipal();
        // 用户权限
        Set<String> permissions = new HashSet<String>();
        List<Menu> authList  = userService.findAuthByUserId(sysUserDetails.getUserId());
        authList.forEach(auth ->{
            permissions.add(auth.getPermission());
        });

        // 判断是否拥有权限
        if (permissions.contains(permission.toString())) {
            return true;
        }
        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId,
                                 String targetType, Object permission) {
        return false;
    }
}
